package com.dsr.service.impl;

import com.dsr.consts.PageResult;
import com.dsr.consts.Result;
import com.dsr.consts.e.UserProperty;
import com.dsr.dao.AddressDao;
import com.dsr.entity.Address;
import com.dsr.entity.Flower;
import com.dsr.exception.FlowerException;
import com.dsr.service.AddressService;
import com.dsr.util.BasicUtil;
import com.dsr.util.IdWorker;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * (Address)表服务实现类
 *
 * @author dsrdiscount_card
 * @since 2020-09-10
 */
@Service("addressService")
public class AddressServiceImpl implements AddressService {
    @Autowired
    private AddressDao addressDao;

    @Autowired
    private IdWorker idWorker;


    @Override
    public Result getEntity(String id) {
        Address entity = addressDao.selectByPrimaryKey(id);
        return Result.success(entity);
    }

    @Override
    public Result save(Address address) {
        address.setId(String.valueOf(idWorker.nextId()));
        address.setUserId(BasicUtil.getToken(UserProperty.USER_ID));
        addressDao.insertSelective(address);
        return Result.success("保存成功");
    }

    @Override
    public Result update(Address address) {
        addressDao.updateByPrimaryKeySelective(address);
        return Result.success("修改成功");

    }

    @Override
    public Result delete(String id) {
        if (StringUtils.isNotEmpty(id)) {
            List<String> ids = Arrays.asList(id.split(","));
            Example example = new Example(Address.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andIn("id", ids);
            addressDao.deleteByExample(example);
            return Result.success("删除成功");
        }
        return Result.error("请选择要删除的行");
    }

    @Override
    public Result query(int page, int size, Address address) {
        PageHelper.startPage(page, size);
        List<Address> entityList = addressDao.select(address);
        PageInfo<Address> pageInfo = new PageInfo<>(entityList);
        return Result.success(new PageResult<Address>(pageInfo.getTotal(), pageInfo.getList()));
    }

    @Override
    public Result list() {
        Address address = new Address();
        String userId = BasicUtil.getToken(UserProperty.USER_ID);
        if(StringUtils.isEmpty(userId)){
            throw new FlowerException(HttpStatus.NETWORK_AUTHENTICATION_REQUIRED,"登录失效");
        }
        address.setUserId(userId);
        return Result.success(addressDao.select(address));
    }
}